package model

import (
	"gorm.io/gorm"
	"week3zk-project/rpc/global"
)

type Goods struct {
	gorm.Model
	GoodsImg    string  `gorm:"type:varchar(20);not null;"`
	GoodsTitle  string  `gorm:"type:varchar(40);not null;"`
	GoodsPrice  float64 `gorm:"type:decimal(10,2);not null;"`
	GoodsStock  int64   `gorm:"type:int(3);not null;"`
	SalesVolume int64   `gorm:"type:int(3);not null;"`
	Status      string  `gorm:"type:varchar(20);not null;comment:1 已上架、2 已下架、3 待审核"`
}

type Classify struct {
	GoodsTitle string `gorm:"type:varchar(40);not null;"`
	Colour     string `gorm:"type:varchar(40);not null;"`
	Size       string `gorm:"type:varchar(20);not null;"`
}

func (g *Goods) Create() error {
	return global.DB.Create(&g).Error
}

func (g *Goods) List(keyword string, page, pageSize int64) error {
	return global.DB.Where("goods_title like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&g).Error
}

func Paginate(page, pageSize int64) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(int(offset)).Limit(int(pageSize))
	}
}
